/*
 * GLOBAL VAIRABLES DEFINITION
 */

/*
 * MAIN FUNCTION, PROGRAM ENTRENCE
 */
document.observe('dom:loaded',function(){
    // EVERY PAGE MAY HAVE ONE INIT FUNCTION TO INIT PAGE DISPALY
    if(typeof initPage != "undefined" && Object.isFunction(initPage) ){
        initPage();
    }
});

function setXY( ev ) {
    ev = ev || window.event;
    var position = getMousePositionOnMap( ev );
    $('x_pos').setValue(position.x);
    $('y_pos').setValue(position.y);
}

function showMarker( ev ) {
    ev = ev || window.event;
    var position = getMousePosition( ev );
    var marker = $('marker');
    var menu = $('menu');
    var singleMenu = $('single_menu');
    var sendMsgDialog = $('send_msg_dialog');
    var sendFileDialog = $('send_file_dialog');
    var sendSingleMsgDialog = $('send_single_msg_dialog');
    var sendSingleFileDialog = $('send_single_file_dialog');
    var userListDiv = $('user_list_div');
    var zoneDetailDiv = $('zone_detail_div');
    menu.hide();
    singleMenu.hide();
    sendMsgDialog.hide();
    sendFileDialog.hide();
    sendSingleMsgDialog.hide();
    sendSingleFileDialog.hide();
    userListDiv.hide();
    zoneDetailDiv.hide();
    marker.show();
    marker.style.left = position.x + 'px';
    marker.style.top = position.y + 'px';
}

function getMousePositionOnMap( ev ) {
    var base = $('svg_map_div');
    var baseX = getX( base );
    var baseY = getY( base );

    if(ev.pageX > baseX || ev.pageY > baseY) {
        return {x:ev.pageX - baseX, y:ev.pageY - baseY};
    }
    
    return {
        x:ev.clientX + document.body.scrollLeft - baseX,
        y:ev.clientY + document.body.scrollTop - baseY
    };
}

function getMousePositionOnMapByDiv( div ) {
    var rawX = getX($(div));
    var rawY = getY($(div));
    var base = $('svg_map_div');
    var baseX = getX( base );
    var baseY = getY( base );

    if(rawX > baseX || rawY > baseY) {
        return {x:rawX - baseX, y:rawY - baseY};
    }

    return {
        x:rawX + document.body.scrollLeft - baseX,
        y:rawY + document.body.scrollTop - baseY
    };
}

function toAbsolute(pos_x, pos_y) {
    var base = $('svg_map_div');
    var baseX = getX( base );
    var baseY = getY( base );

    if(pos_x > baseX || pos_y > baseY) {
        return {x:pos_x + baseX, y:pos_y + baseY};
    }

    return {
        x:pos_x - document.body.scrollLeft + baseX,
        y:pos_y - document.body.scrollTop + baseY
    };

}

function getMousePosition( ev ) {
    if(ev.pageX || ev.pageY) {
        return {x:ev.pageX, y:ev.pageY};
    }

    return {
        x:ev.clientX + document.body.scrollLeft - document.body.clientX,
        y:ev.clientY + document.body.scrollTop - document.body.clientY
    };
}

function getX(elem){
    var x = 0;
    while(elem){
        x = x + elem.offsetLeft;
        elem = elem.offsetParent;
    }
    return x;
}

function getY(elem){
    var y = 0;
    while(elem){
        y = y + elem.offsetTop;
        elem = elem.offsetParent;
    }
    return y;
}

function showMenu( element ) {
    var menu = $('menu');
    menu.show();
    menu.style.left = getX(element) - 20 + 'px';
    menu.style.top = getY(element) - 10 + 'px';
}

function showSendMsgDialog() {
    var element = $('menu');
    var sendMsgDialog = $('send_msg_dialog');
    $('menu').hide();
    sendMsgDialog.show();
    sendMsgDialog.style.left = element.style.left;
    sendMsgDialog.style.top = element.style.top;
}

function showSendFileDialog() {
    var element = $('menu');
    var sendFileDialog = $('send_file_dialog');
    $('menu').hide();
    sendFileDialog.show();
    sendFileDialog.style.left = element.style.left;
    sendFileDialog.style.top = element.style.top;
}

function showBroadcastDialog() {
    var element = $('menu');
    var broadcastDialog = $('broadcast_dialog');
    $('menu').hide();
    broadcastDialog.show();
    broadcastDialog.style.left = element.style.left;
    broadcastDialog.style.top = element.style.top;
}

function sendMsg() {
    var msgText = $F('short_msg');
    var reqUrl = "Upload.do?action=SEND_MESSAGE";

    var params = new Hash();
    params.set("message", msgText);
    params.set("pos_x", getMousePositionOnMapByDiv('marker').x);
    params.set("pos_y", getMousePositionOnMapByDiv('marker').y);
    
    // GET DATA FROM SERVER
    new Ajax.Request(reqUrl,
    {
        method : "post",
        parameters : params.toQueryString(),
        requestHeaders : {
            Accept : "application/json"
        },
        onCreate: function(){
            show_send_msg('loading_send_msg', '');
        },

        onSuccess : function ( transport ) {
            var json = transport.responseText.evalJSON( true );
            
            if ( json.RETURN ) {
                show_success_msg('loading_send_msg', '已发出');
            } else {
                show_error_msg('loading_send_msg', '发送失败');
            }
        },

        onComplete : function () {
            $('short_msg').setValue('');
            $('loading_send_msg').innerHTML = '';
            $('loading_send_msg').className = '';
            $('send_msg_dialog').hide();
        }
    });
}

function broadcast() {

    var broadcastContent = $F('broadcast_content');
    var reqUrl = "Voice.do?action=BROADCAST";

    var params = new Hash();
    params.set("speech", broadcastContent);

    // GET DATA FROM SERVER
    new Ajax.Request(reqUrl,
    {
        method : "post",
        parameters : params.toQueryString(),
        requestHeaders : {
            Accept : "application/json"
        },
        onCreate: function(){
            show_send_msg('loading_broadcast', '广播中...');
        },

        onSuccess : function ( transport ) {
            var json = transport.responseText.evalJSON( true );

            if ( json.RETURN ) {
                show_success_msg('loading_broadcast', '');
            } else {
                show_error_msg('loading_send_msg', '广播失败');
            }
        },

        onComplete : function () {
            $('broadcast_content').setValue('');
            $('loading_broadcast').innerHTML = '';
            $('loading_broadcast').className = '';
            $('broadcast_dialog').hide();
        }
    });
}

function searchUser( elem ) {

    var posX = getX(elem);
    var posY = getY(elem);
    var reqUrl = "Search.do?action=SEARCH_USER";

    var params = new Hash();
    params.set("pos_x", posX);
    params.set("pos_y", posY);

    // GET DATA FROM SERVER
    new Ajax.Request(reqUrl,
    {
        method : "post",
        parameters : params.toQueryString(),
        requestHeaders : {
            Accept : "application/json"
        },
        onCreate: function(){
        },

        onSuccess : function ( transport ) {
            var json = transport.responseText.evalJSON( true );
            
            if ( json.RETURN ) {
                var userListDiv = $('user_list_div');
                userListDiv.show();
                userListDiv.style.left = posX + 'px';
                userListDiv.style.top = posY + 'px';
                showUserListDiv(json.terminalList);
            } else {
                
            }
        },

        onComplete : function () {
        }
    });
}

function showZoneDetail( elem ) {

    var posX = getX(elem);
    var posY = getY(elem);
    var reqUrl = "Search.do?action=SEARCH_USER";

    var params = new Hash();
    params.set("pos_x", posX);
    params.set("pos_y", posY);

    // GET DATA FROM SERVER
    new Ajax.Request(reqUrl,
    {
        method : "post",
        parameters : params.toQueryString(),
        requestHeaders : {
            Accept : "application/json"
        },
        onCreate: function(){
        },

        onSuccess : function ( transport ) {
            var json = transport.responseText.evalJSON( true );

            if ( json.RETURN ) {
                var zoneDetailDiv = $('zone_detail_div');
                zoneDetailDiv.show();
                zoneDetailDiv.style.left = posX + 'px';
                zoneDetailDiv.style.top = posY + 'px';
                $('zone_detail').update('区域信息:' + json.zone + '<br>部署设备:' + json.node);
            } else {

            }
        },

        onComplete : function () {
        }
    });
}

function showUserListDiv( data ) {
    $('user_list').update();
    if (data == undefined || typeof data == 'object') {
        $('user_list').insert('<li>该区域无用户&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li>');
        return;
    }
    for (var i=0; i<data.length; i++) {
        $('user_list').insert('<li>Name:' + data[i].userName + '&nbsp;&nbsp;' + 'Addr:' + data[i].bluetoothAddr + '</li>');
    }
}

//var dummyData1 = {'id': '123', 'posX' : '300', 'posY' : '300'};
//var dummyData2 = {'id': '1234', 'posX' : '400', 'posY' : '400'};
//
//var dummy = new Array();
//dummy[0] = dummyData1;
//dummy[1] = dummyData2;

function showAllUserList( data ) {
//    data = dummy;
    if (typeof data == 'undefined') {
        return;
    }
    for (var i=0; i<data.length; i++) {
        var elem = null;
        if ($(data[i].id) == undefined) {
            elem = new Element('div', {'id': data[i].id, 'style' : 'position:absolute; z-index:50'});
            document.body.appendChild( elem );
            elem.update('<a href="#">(0)</a><br><img src="images/user_icon.gif">')
        } else {
            elem = $(data[i].id);
        }
        elem.style.top = toAbsolute(data[i].posX, data[i].posY).x + 'px';
        elem.style.left = toAbsolute(data[i].posX, data[i].posY).y + 'px';

        elem.observe('mousedown', function (ev) {
            if (ev.button == 2) {
                showSingleMenu(this);
            }
        });
    }
}

function monitor() {
    var reqUrl = "Search.do?action=SEARCH_ALL";

    // GET DATA FROM SERVER
    new Ajax.Request(reqUrl,
    {
        method : "post",
        parameters : '',
        requestHeaders : {
            Accept : "application/json"
        },
        onCreate: function(){
        },

        onSuccess : function ( transport ) {         
            var json = transport.responseText.evalJSON( true );
            if ( json.RETURN ) {
                showAllUserList( json.terminalList );
            } else {

            }
        },

        onComplete : function () {
        }
    });
}

function showSingleMenu( element ) {
    var menu = $('single_menu');
    $('hidden_user_id').setValue(element.id);
    menu.show();
    menu.style.left = getX(element) - 20 + 'px';
    menu.style.top = getY(element) - 10 + 'px';
}

function showSendSingleMsgDialog() {
    var element = $('single_menu');
    var sendMsgDialog = $('send_single_msg_dialog');
    $('single_menu').hide();
    sendMsgDialog.show();
    sendMsgDialog.style.left = element.style.left;
    sendMsgDialog.style.top = element.style.top;
}

function showSendSingleSmsDialog() {
    var element = $('single_menu');
    var sendSmsDialog = $('send_single_sms_dialog');
    $('single_menu').hide();
    sendSmsDialog.show();
    sendSmsDialog.style.left = element.style.left;
    sendSmsDialog.style.top = element.style.top;
}

function showSendSingleFileDialog() {
    var element = $('single_menu');
    var sendMsgDialog = $('send_single_file_dialog');
    $('single_menu').hide();
    sendMsgDialog.show();
    sendMsgDialog.style.left = element.style.left;
    sendMsgDialog.style.top = element.style.top;
}

function sendSingleMsg() {

    var msgText = $F('single_short_msg');
    var reqUrl = "Upload.do?action=SEND_SINGLE_MESSAGE";

    var params = new Hash();
    params.set("message", msgText);
    params.set('user', $F('hidden_user_id'));

    // GET DATA FROM SERVER
    new Ajax.Request(reqUrl,
    {
        method : "post",
        parameters : params.toQueryString(),
        requestHeaders : {
            Accept : "application/json"
        },
        onCreate: function(){
            show_send_msg('single_loading_send_msg', '');
        },

        onSuccess : function ( transport ) {
            var json = transport.responseText.evalJSON( true );

            if ( json.RETURN ) {
                show_success_msg('single_loading_send_msg', '已发出');
            } else {
                show_error_msg('single_loading_send_msg', '发送失败');
            }
        },

        onComplete : function () {
            $('single_short_msg').setValue('');
            $('single_loading_send_msg').innerHTML = '';
            $('single_loading_send_msg').className = '';
            $('send_single_msg_dialog').hide();
        }
    });
}

function sendSingleSms() {

    var msgText = $F('sms');
    var reqUrl = "Sms.do?action=SEND";

    var params = new Hash();
    params.set("tel", $F('tel'));
    params.set('sms', $F('sms'));

    // GET DATA FROM SERVER
    new Ajax.Request(reqUrl,
    {
        method : "post",
        parameters : params.toQueryString(),
        requestHeaders : {
            Accept : "application/json"
        },
        onCreate: function(){
            show_send_msg('single_sms', '');
        },

        onSuccess : function ( transport ) {
            var json = transport.responseText.evalJSON( true );

            if ( json.RETURN ) {
                show_success_msg('single_sms', '已发出');
            } else {
                show_error_msg('single_sms', '发送失败');
            }
        },

        onComplete : function () {
            $('sms').setValue('');
            $('single_sms').innerHTML = '';
            $('single_sms').className = '';
            $('send_single_sms_dialog').hide();
        }
    });
}

function cancelSingleMsg() {
    $('single_short_msg').setValue('');
    $('send_single_msg_dialog').hide();
}

function cancelSingleFile() {
    $('send_single_file_dialog').hide();
}

function cancelMsg() {
    $('short_msg').setValue('');
    $('send_msg_dialog').hide();
}

function cancelFile() {
    $('send_file_dialog').hide();
}

function cancel( id ) {
    $(id).hide();
}

function callBack( msg ) {
    show_success_msg('upload_message', msg);
}
// This function is for stripping leading and trailing spaces
String.prototype.trim = function () {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

Object.extend(String.prototype, {
    templateDecode: function() {
        var decoded = this.replace(/#%7B([a-zA-Z0-9_-]+)%7D/gi, "#{$1}");
        return decoded;
    }
});